package base.thio.zip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipCompress {
	public static void main(String[] args) throws Exception{
		String target="d:test.zip";
		FileOutputStream f=new FileOutputStream(target);
		CheckedOutputStream csum=new CheckedOutputStream(f, new Adler32());
		ZipOutputStream zos=new ZipOutputStream(csum);
		BufferedOutputStream out=new BufferedOutputStream(zos);
		
		zos.setComment("a test of java zipping");
		
		List<String> paths=new ArrayList<String>();
		paths.add("d:HelloWorld.java");
		paths.add("d:a.txt");
		for(String arg:paths){
			System.out.println("wirting file "+arg);
			BufferedReader in=new BufferedReader(new FileReader(arg));
			zos.putNextEntry(new ZipEntry(arg));
			int c;
			while( (c=in.read())!=-1 ){
				out.write(c);
			}
			in.close();
			out.flush();
		}
		out.close();
		
		System.out.println("CheckSum: "+csum.getChecksum().getValue());
		
		System.out.println("Reading file");
		FileInputStream fi=new FileInputStream(target);
		CheckedInputStream csumi=new CheckedInputStream(fi, new Adler32());
		
		ZipInputStream in2=new ZipInputStream(csumi);
		
		BufferedInputStream bis=new BufferedInputStream(in2);
		
		ZipEntry ze;
		
		while ( (ze=in2.getNextEntry())!=null ) {
			System.out.println("Reading file "+ze);
			int x;
			while( (x=bis.read())!=-1 ){
				System.out.print((char)x);
			}
			System.out.println();
		}
		
		if(paths.size()==1){
			System.out.println("Checksum: "+csumi.getChecksum().getValue());
		}
		ZipFile zf=new ZipFile(target);
		Enumeration e=zf.entries();
		while(e.hasMoreElements()){
			ZipEntry ze2=(ZipEntry) e.nextElement();
			System.out.println("File: "+ze2);
			int x;
			while( (x=bis.read())!=-1 ){
				System.out.print((char)x);
			}
			System.out.println();
		}
		
		
		
	}
}
